package com.gyt.framework.web;

import com.gyt.framework.common.utils.RenderUtil;
import com.gyt.framework.exception.BaseException;
import com.gyt.framework.response.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author created by v_yantgao
 * @Date 2021/1/6 19:22
 */
public class BaseController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {

        this.request = request;

        this.response = response;

        this.session = request.getSession();
    }

    /**
     * 异常处理
     * @param request
     * @param response
     * @param e
     * @throws IOException
     */
    @ExceptionHandler(Exception.class)
    public void handleAllException(HttpServletRequest request, HttpServletResponse response,
                                   Exception e) throws IOException {
        String message = e.getMessage();
        if (message == null) {
            message = e.getClass().getName();
        }
        logger.error("handleAllException message:{},e:{}", message, e);
        Response result;
        if (e instanceof BaseException) {
            result = Response.error((BaseException) e, null);
        } else {
            result = Response.error(Response.CODE_ERROR, message, null);
        }
        RenderUtil.renderJSON(response, result);
    }
}
